package com.baijiayun.liveuibase.widgets.dialog;

import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;

import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.utils.DisplayUtils;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

public class QuestionDialogFragment extends DialogFragment {
    public static final String BUNDLE_DATA_URL = "bundle_data_url";
    private static final int DIALOG_WIDTH_PX = 350;
    private static final int DIALOG_HEIGHT_PX = 500;
    private WebView webview;
    private ProgressBar progressBar;
    private float downY;

    public static QuestionDialogFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString(BUNDLE_DATA_URL, url);
        QuestionDialogFragment fragment = new QuestionDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().setCancelable(true);
        return inflater.inflate(R.layout.bjy_base_fragment_dlg_webview, container, false);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.BJYBaseDialogFullScreen);
    }
    private void keepAboveKeyboard(final View root) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect rect = new Rect();
            root.getWindowVisibleDisplayFrame(rect);
            int rootInvisibleHeight = root.getRootView().getBottom() - rect.bottom;
            //认定大于200弹出的是软键盘
            if (rootInvisibleHeight > 150) {
                int srollHeight = (int) (downY + 80 - rect.bottom);
                if (srollHeight > 0) {
                    root.scrollTo(0, srollHeight);
                } else {
                    root.scrollTo(0, 0);
                }
            } else {
                root.scrollTo(0, 0);
            }
        });
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        keepAboveKeyboard(view);
    }
    @SuppressLint("ClickableViewAccessibility")
    private void initView(View view) {
        webview = view.findViewById(R.id.webview);
        progressBar = view.findViewById(R.id.pb_webview);
        webview.setOnTouchListener((v, event) -> {
            downY = event.getRawY();
            return false;
        });
        String url = getArguments() == null ? "" : getArguments().getString(BUNDLE_DATA_URL, "");
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int heightPixels = metrics.heightPixels;
        int widthPixels = metrics.widthPixels;
        float density = metrics.density;
        float maxScale = Math.min(1.0f * heightPixels / DIALOG_HEIGHT_PX, 1.0f * widthPixels / DIALOG_WIDTH_PX);
        if (DisplayUtils.isPad(getContext())) {
            if (density - 2.0 < 0.001 && density - 2.0 > -0.001) {
                maxScale = maxScale * 78;
            } else {
                maxScale = maxScale * 70;
            }
        } else {
            maxScale = maxScale * 80;
        }
        webview.setInitialScale((int)maxScale);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.addJavascriptInterface(new Jsobj(), "app");
        webview.setBackgroundColor(0);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                webview.loadUrl("about:blank");
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
                sslErrorHandler.proceed();
            }
        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress > 0 && newProgress != 100) {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                } else {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });
        webview.loadUrl(url);
    }

    class Jsobj {
        @JavascriptInterface
        public void close(boolean success) {
            if (onSubmitQuestionListener != null) {
                onSubmitQuestionListener.onSubmit(success);
            }
            dismiss();
        }
    }

    @Override
    public void dismiss() {
        if (getDialog() != null) {
            try {
                if (isAdded()) {
                    super.dismiss();
                }
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (manager != null && (getDialog() == null || !getDialog().isShowing())) {
            try {
                if (!isAdded()) {
                    super.show(manager, tag);
                }
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (webview != null) {
            webview.destroy();
        }
    }

    public OnSubmitQuestionListener onSubmitQuestionListener;

    public void setOnSubmitQuestionListener(OnSubmitQuestionListener onSubmitQuestionListener) {
        this.onSubmitQuestionListener = onSubmitQuestionListener;
    }

    public interface OnSubmitQuestionListener {
        void onSubmit(boolean isSubmit);
    }
}
